import React, { useEffect, useState } from 'react';
import { Modal, Spin } from 'antd';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';
import { useTablePipeline } from 'ali-react-table';
import { AntdBaseTable } from '@/base/TBaseTable';
import { TRDefault } from '@/components/index.js';
import { ExplainTitle } from '../../../components';
import type {
  IFindStrategyPriceForecastItemType,
  IFindStrategyPriceForecastListType,
} from '../../../type';
import { ITitleType, IStrategyBenefitDetailKeyType, IColumnsKeyType } from '../../../type';
import { TIME_ENUM, ToFixed } from '../../../tool';
import { strategyBenefitTitleMap, defaultPointerNum, columnsKeysList } from '../../../dictionary';
import styles from './index.less';

interface IProps {
  /**
   * isError
   */
  error?: boolean;
  /**
   * data
   */
  data?: IFindStrategyPriceForecastItemType;
  /**
   * 标题类型
   */
  titleType: ITitleType.CURRENTSTRATEGY | ITitleType.AISTRATEGY;
  onPress: (data: Record<string, any>) => void;
}

const StrategyBenefitDetailModalComponent = (props: IProps) => {
  const pointerNums = TIME_ENUM(defaultPointerNum);
  const { onPress, data, error = false, titleType = ITitleType.CURRENTSTRATEGY } = props;
  const [list, setList] = useState<IFindStrategyPriceForecastListType[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const _titleInfo = strategyBenefitTitleMap[titleType];
  const [visible, setVisible] = useState<boolean>(true);

  useEffect(() => {
    if (data) {
      setLoading(true);
      const _list: IFindStrategyPriceForecastListType[] = [];
      const obj: IFindStrategyPriceForecastListType = {
        timeOrder: '总计',
        ...data[IStrategyBenefitDetailKeyType.TOTAL],
      };
      _list.push(obj);
      pointerNums.forEach((item, index) => {
        _list.push({
          timeOrder: item,
          [IStrategyBenefitDetailKeyType.EARNINGS]: (data[IStrategyBenefitDetailKeyType.EARNINGS] ||
            [])[index],
          [IStrategyBenefitDetailKeyType.RISK]: (data[IStrategyBenefitDetailKeyType.RISK] || [])[
            index
          ],
          [IStrategyBenefitDetailKeyType.PRICE_DIFFF_ORECAST]: (data[
            IStrategyBenefitDetailKeyType.PRICE_DIFFF_ORECAST
          ] || [])[index],
          [IStrategyBenefitDetailKeyType.PRICE_DIFF_BELIEVE]: (data[
            IStrategyBenefitDetailKeyType.PRICE_DIFF_BELIEVE
          ] || [])[index],
          [IStrategyBenefitDetailKeyType.SIM_ADJUSTMENT]: (data[
            IStrategyBenefitDetailKeyType.SIM_ADJUSTMENT
          ] || [])[index],
        });
      });
      setList(_list);
    }
    setLoading(false);
  }, [data]);

  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  const executeStatusTitle = (title: string, hintText: string) => {
    return (
      <div className={styles.executeStatusTitle}>
        <ExplainTitle title={title} hintText={hintText} />
      </div>
    );
  };

  const columns = () => {
    const _columns = columnsKeysList.map((item) => {
      const { persion, hintText = '', name = '', ...rest } = item;
      return {
        ...rest,
        name:
          item?.code === IColumnsKeyType.SIM_ADJUSTMENT ||
          item?.code === IColumnsKeyType.PRICE_DIFFF_ORECAST
            ? executeStatusTitle(name, hintText)
            : name,
        align: 'center',
        width: 100,
        render(v: string | number) {
          return (
            <div>
              {v || v === 0
                ? persion || persion === 0
                  ? ToFixed(
                      item.code === IColumnsKeyType.PRICE_DIFF_BELIEVE ? Number(v) * 100 : v,
                      persion,
                    )
                  : v
                : '-'}
            </div>
          );
        },
      };
    });
    return _columns;
  };

  const pipeline = useTablePipeline({})
    .input({ dataSource: list, columns: columns() as any })
    .primaryKey('timeOrder')
    .appendRowPropsGetter((): any => {
      const color = '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });
  return (
    <Modal
      className={styles.modal}
      centered
      width={800}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <div className={styles.left}>
            <img src={planIcon} className={styles.titleLogo} />
            <span className={styles.title}>{_titleInfo.detailTitle}</span>
          </div>
        </div>
      }
      onCancel={_onCancel}
      footer={null}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin />
        ) : error ? (
          <TRDefault type={'error'} message={'系统异常'} />
        ) : list.length ? (
          <div className={styles.table}>
            <AntdBaseTable
              useVirtual={{ horizontal: true, vertical: true, header: false }}
              style={{
                '--row-height': '28px',
                // '--header-bgcolor': '#383C3E',
                '--header-row-height': '28px',
                '--cell-padding': '4px 16px',
                '--cell-border-vertical': '1px solid #4E5154',
                '--header-cell-border-vertical': '1px solid #4E5154',
                '--hover-bgcolor': '#222629',
              }}
              {...pipeline.getProps()}
            />
          </div>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </Modal>
  );
};

class StrategyBenefitDetailModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <StrategyBenefitDetailModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new StrategyBenefitDetailModal();
